//
//  HomeTableViewController.swift
//  Weibo
//
//  Created by 李亚乐 on 15/12/6.
//  Copyright © 2015年 李亚乐. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 原创微博 Cell 重用ID
let WBStatusCellNormalId = "WBStatusCellNormalId"
/// 转发微博 Cell 重用ID
let WBStatusCellRetweetedId = "WBStatusCellRetweetedId"


//MARK: - 主页 tableView 控制器
class HomeTableViewController: VisitorTableViewController {
    
    /// 微博列表数组 视图模型
    private lazy var statusListViewModel = StatusListViewModel()
    
    // MARK: - 视图生命周期
    override func viewDidLoad() {
        super.viewDidLoad()

        //没登陆显示访客视图
        if !UserAccountViewModel.sharedUserAccount.userLogon {
            visitView?.setupInfo("关注一些人，回这里看看有什么惊喜", imageName: nil)
            return
        }
        
        //准备表格
        prepareTableView()
        
        //加载微博数据
        loadData()
        
        //注册通知中心
        addNotificationCenter()
    }
    
    /// 注册通知中心
    private func addNotificationCenter() {
        
        NSNotificationCenter.defaultCenter().addObserverForName(WBNotificationStatusSelectedPhoto, object: nil, queue: nil) { [weak self] (notification) -> Void in
            
            guard let indexpath = notification.userInfo?[WBUserInfoKeyStatusSelectedPhotoIndex] as? NSIndexPath else {
                return
            }
            guard let urls = notification.userInfo?[WBUserInfoKeyStatusSelectedPhotoURLs] as? [NSURL] else {
                return
            }
            
            guard let view = notification.object as? PhotoBrowserPresentDelegate else {
                return
            }
            
            
            let picBrowser = PictrueBrowserViewController(indexpath: indexpath, urls: urls)
            
            picBrowser.modalPresentationStyle = UIModalPresentationStyle.Custom
            /*
            case CoverVertical  底部推出
            case FlipHorizontal 水平翻转
            case CrossDissolve  淡入淡出
            case PartialCurl    书本翻页
            picBrowser.modalTransitionStyle = UIModalTransitionStyle.PartialCurl
            */
            
            /// 转场代理
            picBrowser.transitioningDelegate = self?.photoBrowserAnimator
            
            self?.photoBrowserAnimator.setDelegateAndParameters(view, dismissDelegate: picBrowser, indexpath: indexpath)
            
            /// modal 转场
            self?.presentViewController(picBrowser, animated: true, completion: nil)
        }

    }
    
    /// 结构方法
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /// 准备表格视图
    private func prepareTableView() {
        
        //注册可重用标识
        tableView.registerClass(StatusRetweetedCell.self, forCellReuseIdentifier: WBStatusCellRetweetedId)
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: WBStatusCellNormalId)
        
        //取消分割线
        tableView.separatorStyle = .None
        //设置预估行高
        tableView.estimatedRowHeight = 400
        
        //创建刷新菊花
        refreshControl = WBRfreshControl()
        //添加监听方法
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        //添加底部刷新视图
        tableView.tableFooterView = pullupView

    }
    
    /// 加载数据
    @objc private func loadData() {
        
        refreshControl?.beginRefreshing()

        /// 加载数据
        statusListViewModel.loadData(pullupView.isAnimating()) { (isSuccessed) -> () in

            //停止菊花刷新
            self.refreshControl?.endRefreshing()
            self.pullupView.stopAnimating()
            
            if !isSuccessed {
                SVProgressHUD.showErrorWithStatus("网络不给力...")
                return
            }
            
//            返回数据
//            print(self.statusListViewModel.statusList)
            //刷新表格
            self.tableView.reloadData()
        }
    }
    
    // MARK: - 懒加载底部刷新控件
    private lazy var pullupView: UIActivityIndicatorView = {
        
        let aiv = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        aiv.color = UIColor.lightGrayColor()
        return aiv
    }()
    /// 转场动画代理
    private lazy var photoBrowserAnimator: PhotoBrowserAnimator = PhotoBrowserAnimator()
}

// MARK: - 数据源, 代理方法
extension HomeTableViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListViewModel.statusList.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let vm = statusListViewModel.statusList[indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(vm.cellID, forIndexPath: indexPath) as! StatusCell
        
        //Cell 的视图模型赋值
        cell.viewModel = vm
        
        if indexPath.row == statusListViewModel.statusList.count - 1 && !pullupView.isAnimating() {
            
            //开始底部刷新动画
            pullupView.startAnimating()
            loadData()
        }
        
        return cell
    }
    
    /// 通过模型属性计算 Cell 行高
    ///
    /// - parameter tableView: tableView
    /// - parameter indexPath: indexPath
    ///
    /// - returns: Cell 的行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        let viewmodel = statusListViewModel.statusList[indexPath.row]
        
        return viewmodel.rowHeight
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print(indexPath.row)
    }
}





